/*
 * Copyright (c) 2018-2999 湖南洛云网络科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.security.api.filter;

import cn.hutool.core.util.StrUtil;
import com.yami.shop.bean.model.Station;
import com.yami.shop.security.api.model.YamiUser;
import com.yami.shop.security.comment.exception.YamiAuthFilterException;
import com.yami.shop.security.comment.filter.YamiAuthenticationProcessingFilter;
import com.yami.shop.security.comment.token.AuthenticationToken;
import com.yami.shop.service.StationService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 自定义登陆filter
 * 统一第三方登陆
 * @author LGH
 */
@Component
public class StationLoginAuthenticationFilter extends YamiAuthenticationProcessingFilter {

    private final StationService stationService;
    private final PasswordEncoder passwordEncoder;


    public StationLoginAuthenticationFilter(StationService stationService,PasswordEncoder passwordEncoder) {
        super("/stationLogin");
        this.stationService = stationService;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    protected UserDetails getUserDetails(AuthenticationToken authentication) {
        Station station = stationService.getStationInfoByAccount(authentication.getPrincipal());
        if (Objects.isNull(station) || StrUtil.isBlank(station.getPassword()) || !passwordEncoder.matches(String.valueOf(authentication.getCredentials()),station.getPassword())){
            // 账号或密码错误，请重新输入
            throw new YamiAuthFilterException("yami.user.account.error");
        }
        if (!Objects.equals(station.getStatus(),1)){
            // 该自提点已关闭，请联系管理员
             throw new YamiAuthFilterException("yami.shop.station.close");
        }
        YamiUser yamiUser = new YamiUser();
        yamiUser.setEnabled(true);
        yamiUser.setStationId(station.getStationId());
        yamiUser.setShopId(station.getShopId());
        return yamiUser;
    }


}
